<template>
  <div style="height: 100%">
    <div class="flex_cm container" style="height: 100%">
      <search
        :form_data="header_list"
        @changeIsShow="
          (e) => {
            header_list[e].isShow = !header_list[e].isShow;
          }
        "
        @search="search_key"
        @reset="
          header_list.forEach((item) => {
            item.value = '';
          }),
            search_key()
        "
      ></search>
      <div class="p_0_10 bg_fff flex1">
        <div class="flex_js p_10_0">
          <div class="c_666 fw">账号管理</div>
          <div class="flex">
            <el-button
              type="primary"
              @click="(show_share_box = true), get_invitation_list();"
              >邀请</el-button
            >

            <setTable
              :data="header_list"
              :height_size="height_size"
              @changeShowTable="
                (e) => {
                  header_list[e].showTable = !header_list[e].showTable;
                }
              "
              @resetTableSet="
                () => {
                  header_list.forEach((item) => {
                    item.showTable = true;
                  });
                }
              "
              @changeHeightSize="
                (e) => {
                  height_size = e;
                }
              "
            ></setTable>
          </div>
        </div>
        <el-table
          style="text-align: center"
          :data="list"
          :max-height="max_height"
          border
          highlight-current-row
          v-loading="loading"
          :default-sort="{ prop: 'name', order: 'descending' }"
          :row-style="{
            height: height_size == 2 ? '50px' : '',
          }"
          :cell-style="{
            padding: height_size == 3 ? '0' : '',
          }"
        >
          <el-table-column type="index" label="序号" width="80px"></el-table-column>
          <el-table-column
            label="用户名"
            prop="name"
            sortable
            v-if="header_list[0].showTable"
            key="用户名"
          ></el-table-column>
          <el-table-column
            label="用户昵称"
            v-if="header_list[1].showTable"
            key="用户昵称"
            sortable
            prop="nickName"
          ></el-table-column>
          <el-table-column
            label="微信"
            v-if="header_list[2].showTable"
            key="微信"
            sortable
            prop="wechat"
          ></el-table-column>
          <el-table-column
            label="手机号"
            v-if="header_list[3].showTable"
            key="手机号"
            sortable
            prop="phone"
          ></el-table-column>
          <el-table-column
            label="角色"
            sortable
            prop="roleName"
            v-if="header_list[4].showTable"
            key="角色"
          >
            <template #default="scope: any">
              <div v-if="scope.row.isAdmin">管理员</div>
              <div v-else>{{ scope.row.roleName }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="部门"
            sortable
            prop="deptName"
            v-if="header_list[5].showTable"
            key="部门"
          ></el-table-column>
          <el-table-column
            label="状态"
            sortable
            prop="status"
            v-if="header_list[6].showTable"
            key="状态"
          >
            <template #default="scope: any">
              <div v-if="scope.row.status == 2" style="color: #3580eb">已启用</div>
              <div v-if="scope.row.status == 3">已停用</div>
              <div v-if="scope.row.status == 1">待确认</div>
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            sortable
            prop="remark"
            v-if="header_list[7].showTable"
            key="备注"
            ><template #default="scope: any"
              ><div class="text_over">
                <el-tooltip :content="scope.row.remark" placement="bottom">
                  {{ scope.row.remark }}
                </el-tooltip>
              </div></template
            ></el-table-column
          >
          <el-table-column label="操作" width="120">
            <template #default="scope: any">
              <div class="flex_cc" style="column-gap: 20px">
                <el-tooltip
                  v-if="(has_role_list[1] as any).has_role"
                  content="编辑"
                  placement="bottom"
                >
                  <svgBtn
                    icon="table_edit"
                    style="font-size: 20px"
                    @click="update_list(scope)"
                  ></svgBtn>
                </el-tooltip>
                <el-tooltip
                  v-if="(has_role_list[1] as any).has_role && !scope.row.isAdmin"
                  content="删除"
                  placement="bottom"
                >
                  <svgBtn
                    icon="table_delete"
                    style="font-size: 20px"
                    @click="delete_list(scope)"
                  ></svgBtn>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="m_10_0 pagination"
          v-model:currentPage="page_data.current"
          v-model:page-size="page_data.pageSize"
          :page-sizes="[10, 20, 50, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="list_debounce()"
          @current-change="list_debounce()"
        />
      </div>
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="60%"
      @close="resetForm(adduserform)"
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增</h4>
        <h4 v-else>编辑账号</h4>
      </template>
      <template #default>
        <el-form
          :model="add_form_data"
          label-width="100px"
          :rules="rules"
          ref="adduserform"
        >
          <div class="form_box">
            <el-form-item label="手机号" prop="phone">
              <el-input
                disabled
                @input="get_phoneNum"
                v-model="add_form_data.phone"
                placeholder="请输入"
                show-word-limit
                maxlength="11"
              ></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="name">
              <el-input
                disabled
                v-model="add_form_data.name"
                placeholder="请输入"
                show-word-limit
                maxlength="30"
              ></el-input>
            </el-form-item>
            <el-form-item label="昵称">
              <el-input
                disabled
                v-model="add_form_data.nickName"
                placeholder="请输入"
                show-word-limit
                maxlength="30"
              ></el-input>
            </el-form-item>
            <el-form-item label="角色" v-if="!is_admin" prop="roleIds">
              <el-select
                v-model="add_form_data.roleIds"
                multiple
                style="width: 100%"
                class="roleIds"
              >
                <el-option
                  v-for="item in role_list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="部门">
              <el-cascader
                style="width: 100%"
                v-model="add_form_data.deptId"
                :options="depart_list"
                :props="cascader_props"
                clearable
              />
            </el-form-item>
            <!-- <el-form-item label="邮箱">
              <el-input
                disabled
                v-model="add_form_data.email"
                placeholder="请输入"
                show-word-limit
                maxlength="30"
              ></el-input>
            </el-form-item> -->
            <el-form-item label="微信">
              <el-input
                disabled
                v-model="add_form_data.wechat"
                placeholder="请输入"
                show-word-limit
                maxlength="30"
              ></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio
                v-model="add_form_data.status"
                :disabled="add_form_data.status != 1 || is_admin"
                :label="1"
                >待确认</el-radio
              >
              <el-radio v-model="add_form_data.status" :disabled="is_admin" :label="2"
                >已启用</el-radio
              >
              <el-radio v-model="add_form_data.status" :disabled="is_admin" :label="3"
                >已停用</el-radio
              >
            </el-form-item>
            <el-form-item label="首次邀请人">
              <el-input
                v-model="add_form_data.inviter"
                placeholder="请输入"
                disabled
              ></el-input>
            </el-form-item>
          </div>
          <el-form-item label="备注">
            <el-input
              type="textarea"
              resize="none"
              v-model="add_form_data.remark"
              placeholder="请输入"
              show-word-limit
              maxlength="300"
            ></el-input>
          </el-form-item>
          <div class="m_top10 tr">
            <el-button @click="resetForm(adduserform)">取消</el-button>
            <el-button type="primary" :loading="btn_loading" @click="submit(adduserform)"
              >保存</el-button
            >
          </div>
        </el-form>
        <!-- <div>多组织管理</div> -->
      </template>
    </el-drawer>
    <el-drawer
      v-model="show_share_box"
      direction="rtl"
      size="60%"
      :close-on-click-modal="false"
    >
      <template #default>
        <div class="share_box_top border_bottom">
          <div>
            <div
              :class="invitation_page_data.status == 1 ? 'select' : ''"
              @click="(invitation_page_data.status = 1), get_invitation_list();"
            >
              已同意
            </div>
            <div
              :class="invitation_page_data.status == 2 ? 'select' : ''"
              @click="(invitation_page_data.status = 2), get_invitation_list();"
            >
              已拒绝
            </div>
            <div
              :class="invitation_page_data.status == 3 ? 'select' : ''"
              @click="(invitation_page_data.status = 3), get_invitation_list();"
            >
              审核通过
            </div>
            <div
              :class="invitation_page_data.status == 4 ? 'select' : ''"
              @click="(invitation_page_data.status = 4), get_invitation_list();"
            >
              审核拒绝
            </div>
          </div>
          <el-button type="primary" @click="invitation" v-if="has_role_list[3].has_role"
            >邀请新用户</el-button
          >
        </div>
        <el-table class="m_top10 tc" :data="invitation_list" border max-height="800px">
          <el-table-column type="index" label="序号" width="80px"></el-table-column>
          <el-table-column label="用户名">
            <template #default="scope: any">{{ scope.row.member.name }}</template>
          </el-table-column>
          <el-table-column label="操作" v-if="has_role_list[4].has_role">
            <template #default="scope: any">
              <div v-if="scope.row.status == 1">
                <el-button @click="exam_list({ item: scope, type: 3 })">审核</el-button>
                <el-button @click="exam_list({ item: scope, type: 4 })">拒绝</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="m_10_0"
          v-model:currentPage="invitation_page_data.current"
          v-model:page-size="invitation_page_data.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="invitation_total"
          @size-change="invitation_list_debounce()"
          @current-change="invitation_list_debounce()"
        />
      </template>
    </el-drawer>
    <dialog_box
      @submit_delete="submit_delete"
      @submit_edit="submit_edit"
      @close="show_delete_box = false"
      :delete_name="delete_name"
      :show_delete_box="show_delete_box"
      :delete_box_status="delete_box_status"
    ></dialog_box>
  </div>
</template>

<script lang="ts" setup>
import { check_role, handle_search_key, debounce } from "@/utils/check_role"; // 权限校验
import search from "@/view/components/search.vue";
import dialog_box from "@/view/components/dialog_box.vue";
import setTable from "@/view/components/setTable.vue";
import svgBtn from "@/components/svg_button.vue";
import { onMounted, ref, reactive, onUnmounted, computed, nextTick } from "vue";
import { FormInstance, ElMessage, FormRules } from "element-plus";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
import { getCookie } from "@/utils/cookie";
import { useStore } from "vuex";
const store = useStore();
const has_role_list = ref([
  { path: "", has_role: false },
  { path: "user/put", has_role: false },
  { path: "user/delete", has_role: false },
  { path: "invitation/send", has_role: false },
  { path: "invitation/status", has_role: false },
]);
// type FormInstance = InstanceType<typeof ElForm>
const adduserform = ref<FormInstance>();
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  roleIds: [{ type: "array", required: true, message: "请选择角色", trigger: "change" }],
  deptId: [{ type: "array", required: true, message: "请选择部门", trigger: "change" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
});
const cascader_props = { checkStrictly: true, multiple: true };
const list = ref();
const loading = ref(false);
const btn_loading = ref(false);
const show_box = ref(false);
const show_share_box = ref(false); //  邀请列表
const height_size = ref(1);
const max_height = ref();
nextTick(() => {
  max_height.value = window.innerHeight - 310; // 带分页的 table 高度
});
const header_list = ref([
  {
    label: "用户名",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "用户昵称",
    value: "",
    showTable: true,
    type: "input",
    isShow: true,
    options: [],
  },
  {
    label: "微信",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "手机号",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "角色",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "部门",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
  {
    label: "状态",
    value: "",
    showTable: true,
    type: "select",
    isShow: false,
    options: [
      {
        label: "待确认",
        value: "1",
      },
      {
        label: "已启用",
        value: "2",
      },
      {
        label: "已停用",
        value: "3",
      },
    ],
  },
  {
    label: "备注",
    value: "",
    showTable: true,
    type: "input",
    isShow: false,
    options: [],
  },
]);
const page_data = ref({
  current: 1,
  pageSize: 10,
  deptName: "",
  enterpriseId: computed(() => {
    return store.state.enterprise_id != "" // 当前登录企业 vuex > cookie
      ? store.state.enterprise_id
      : getCookie("enterprise_id");
  }),
  status: "",
  name: "",
  nickName: "",
  wechat: "",
  phone: "",
  roleName: "",
  remark: "",
});
const total = ref();
const add_form_data = ref({
  id: "",
  name: "",
  nickName: "",
  deptId: [],
  //   email: '',
  roleIds: [],
  wechat: "",
  phone: "",
  status: 1,
  remark: "",
  inviter: "",
  memberId: "",
});
onMounted(() => {
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item);
  });
  EventBus.on("refresh", () => {
    get_list();
    get_roler_list();
    get_depart_list();
    ElMessage.success("刷新成功！");
  });
  get_list();
  get_roler_list();
  get_depart_list();
});
onUnmounted(() => {
  EventBus.off("refresh");
});
const invitation_page_data = ref({
  current: 1,
  pageSize: 10,
  name: "",
  status: 1,
});
const invitation_list = ref();
const invitation_total = ref();
const get_invitation_list = () => {
  axios
    .request({
      url: serviceApi.invitation_list,
      method: "post",
      data: invitation_page_data.value,
    })
    .then((res) => {
      invitation_list.value = res.data.content;
      invitation_total.value = parseInt(res.data.totalElements);
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
let invitation_list_debounce = debounce(200, get_invitation_list);
const submit_edit = () => {
  if (delete_box_status.value == 3) {
    // 邀请审核通过
    axios
      .request({
        url: serviceApi.exam_invitation + "/" + delete_id.value,
        method: "post",
      })
      .then(() => {
        ElMessage.success("操作成功！");
        setTimeout(() => {
          get_invitation_list();
          get_list();
        }, 1000);
      })
      .catch((err) => {
        ElMessage.error(err);
      });
  } else if (delete_box_status.value == 4) {
    axios
      .request({
        url: serviceApi.refuse_invitation + "/" + delete_id.value,
        method: "post",
      })
      .then(() => {
        ElMessage.success("操作成功！");
        setTimeout(() => {
          get_invitation_list();
          get_list();
        }, 1000);
      })
      .catch((err) => {
        ElMessage.error(err);
      });
  }
  show_delete_box.value = false;
};
const exam_list = (e) => {
  // memberId 删除  id  邀请审核
  delete_id.value = e.item.row.id;
  delete_name.value = e.item.row.member.name;
  delete_box_status.value = e.type;
  show_delete_box.value = true;
};
const invitation = () => {
  axios
    .request({ url: serviceApi.send_invitation, method: "post" })
    .then((res) => {
      console.log(res);
      var url = res.data.sendLink;
      let Oinput = document.createElement("input");
      Oinput.value = url;
      document.body.appendChild(Oinput);
      Oinput.select();
      document.execCommand("copy");
      ElMessage.success("邀请链接复制成功！");
      document.body.removeChild(Oinput);
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const check_phone = ref(false);
const get_phoneNum = (e) => {
  console.log(e);
  if (e.length == 11) {
    var reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    if (reg.test(e)) {
      // 根据手机号获取  用户信息
      axios
        .request({
          url: serviceApi.get_memberInfoByPhone + "?phone=" + e,
          method: "get",
        })
        .then((res) => {});
      check_phone.value = true;
    } else {
      ElMessage.error("请输入正确的手机号！");
    }
  }
};
const depart_list = ref();
const depart_page_data = ref({
  enterpriseId: store.state.enterprise_id,
  isEnable: 1,
  name: "",
  superiorDept: "",
  director: "",
  remark: "",
});
const get_depart_list = () => {
  axios
    .request({
      url: serviceApi.depart_list,
      method: "post",
      data: handle_search_key(depart_page_data.value),
    })
    .then((res) => {
      console.log(res);
      depart_list.value = arrToTree(res.data);
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const role_list = ref();
const get_roler_list = () => {
  axios
    .request({
      url: serviceApi.role_list,
      method: "post",
      data: { current: 1, pageSize: 100 },
    })
    .then((res) => {
      console.log(res);
      role_list.value = res.data.content;
    })
    .catch((error) => {
      ElMessage.error(error);
    });
};
const show_delete_box = ref();
const delete_name = ref();
const delete_id = ref();
const delete_box_status = ref();
const submit_delete = () => {
  axios
    .request({
      url: serviceApi.user_crud + "/" + delete_id.value,
      method: "delete",
    })
    .then(() => {
      ElMessage.success("操作成功！");
      setTimeout(() => {
        show_delete_box.value = false;
        get_list();
      }, 1000);
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const delete_list = (e) => {
  delete_id.value = e.row.memberId;
  delete_name.value = e.row.name;
  show_delete_box.value = true;
  delete_box_status.value = 0;
};
const is_admin = ref(false);
const update_list = (e) => {
  is_admin.value = e.row.isAdmin;
  axios
    .request({
      url: serviceApi.user_crud + "/" + e.row.id,
      method: "get",
    })
    .then((res) => {
      console.log(res);
      add_form_data.value.deptId = res.data.deptIds;
      add_form_data.value.roleIds = res.data.roleIds;
      add_form_data.value.inviter = res.data.pName;
      add_form_data.value = {
        id: e.row.memberId,
        name: e.row.name,
        nickName: e.row.nickName,
        deptId: add_form_data.value.deptId,
        roleIds: add_form_data.value.roleIds,
        wechat: e.row.wechat,
        phone: e.row.phone,
        status: e.row.status,
        remark: e.row.remark,
        inviter: add_form_data.value.inviter,
        memberId: e.row.memberId,
      };
      console.log(add_form_data.value);
      show_box.value = true;
    });
};
const submit = async (formEl: FormInstance | undefined) => {
  // 扁平化 部门id list
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) {
        return;
      }
      btn_loading.value = true;
      let deptId = [];
      add_form_data.value.deptId.forEach((item) => {
        if (Array.isArray(item)) {
          deptId.push(item.at(-1));
        } else {
          deptId.push(item);
        }
      });
      add_form_data.value.deptId = deptId;
      axios
        .request({
          url:
            add_form_data.value.id == ""
              ? serviceApi.user_crud
              : serviceApi.user_crud + "/" + add_form_data.value.id,
          method: add_form_data.value.id == "" ? "post" : "put",
          data: add_form_data.value,
        })
        .then((res) => {
          console.log(res);
          ElMessage.success("操作成功！");
          setTimeout(() => {
            btn_loading.value = false;
            show_box.value = false;
            get_list();
          }, 1000);
        })
        .catch((err) => {
          btn_loading.value = false;
          ElMessage.error(err);
        });
    }
  });
};
const get_list = () => {
  loading.value = true;
  axios
    .request({
      url: serviceApi.user_list,
      method: "post",
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      console.log(res);
      list.value = res.data.content;
      total.value = parseInt(res.data.totalElements);
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      ElMessage.error(err);
    });
};
let list_debounce = debounce(200, get_list);
const search_key = () => {
  console.log(header_list.value[6].value);
  page_data.value = {
    current: 1,
    pageSize: 10,
    name: header_list.value[0].value,
    nickName: header_list.value[1].value,
    wechat: header_list.value[2].value,
    phone: header_list.value[3].value,
    roleName: header_list.value[4].value,
    deptName: header_list.value[5].value,
    enterpriseId: computed(() => {
      return store.state.enterprise_id != "" // 当前登录企业 vuex > cookie
        ? store.state.enterprise_id
        : getCookie("enterprise_id");
    }),
    status: header_list.value[6].value,
    remark: header_list.value[7].value,
  };
  get_list();
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  add_form_data.value = {
    memberId: "",
    id: "",
    name: "",
    nickName: "",
    deptId: [],
    // email: '',
    roleIds: [],
    wechat: "",
    phone: "",
    status: 1,
    remark: "",
    inviter: "",
  };
  show_box.value = false;
};
const arrToTree = (list) => {
  var map = {};
  var result = [];
  list.forEach((item) => {
    map[item.id] = item;
  });
  list.forEach((item) => {
    item.label = item.name;
    item.value = item.id;
    let parent = map[item.parentId];
    if (parent) {
      if (!parent.children) {
        parent.children = [];
      }
      parent.children.push(item);
    } else {
      result.push(item);
    }
  });
  return result;
};
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  align-items: center;
}

.share_box_top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  > div:first-child {
    display: flex;
    > div {
      border: 1px solid #e6e8eb;
      width: 120px;
      height: 48px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
    .select {
      border: 1px solid #3580eb;
      color: #3580eb;
    }
  }
}
.form_box {
  display: flex;
  flex-wrap: wrap;
  > .el-form-item {
    width: 33.3333%;
  }
  :deep(.el-input__inner) {
    padding-right: 11px;
  }
}
</style>
